// cookie.controller.ts
import {
  Controller,
  Post,
  Body,
  Get,
  Param,
  Delete,
  BadRequestException,
  NotFoundException,
  UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { PrismaService } from '../database/prisma.service';
import { ParseIntPipe } from '@nestjs/common';
import { CreateCookieDto } from './dto/create-cookie.dto';
import { CookieResponseDto } from './dto/cookie-response.dto';
import { UploadedFile } from '@nestjs/common';
import { CookiesService } from './cookie.services';
// function parseAsciiStringToBuffer(asciiString: string): Buffer {
//   const byteArray = asciiString.split(',').map(Number); // Convert "91,110,97..." to [91, 110, 97, ...]
//   return Buffer.from(byteArray); // Create Buffer from byte array
// }

@Controller('cookies')
export class CookiesController {
  constructor(
    private readonly prismaService: PrismaService,
    private readonly cookieService: CookiesService,
  ) {}

  // Create Cookie via JSON (string content)
  @Post()
  async createCookie(
    @Body() createCookieDto: CreateCookieDto,
  ): Promise<CookieResponseDto> {
    try {
      const { name, content, platformId } = createCookieDto;
      const platformExists = await this.prismaService.platform.findUnique({
        where: { id: platformId },
      });
      if (!platformExists) {
        throw new BadRequestException(
          `Platform with ID ${platformId} not found`,
        );
      }

      const cookie = await this.prismaService.cookie.create({
        data: {
          name,
          content: content.toString(), // Default UTF-8 encoding
          platformId,
        },
      });

      return {
        id: cookie.id,
        name: cookie.name,
        filename: cookie.filename,
        content: cookie.content.toString(), // No args, defaults to 'utf8'
        platformId: cookie.platformId,
        platformName: platformExists.name,
        createdAt: cookie.createdAt,
      };
    } catch (error) {
      throw new BadRequestException(
        `Failed to create cookie: ${error.message}`,
      );
    }
  }

  // Create Cookie via File Upload
  @Post('upload')
  @UseInterceptors(FileInterceptor('file'))
  async uploadCookie(
    @UploadedFile() file: Express.Multer.File,
    @Body('platformId', ParseIntPipe) platformId: number,
    @Body('name') name: string,
  ): Promise<string> {
    try {
      if (!file) {
        throw new BadRequestException('No file uploaded');
      }
      if (!platformId) {
        throw new BadRequestException('platformId is required');
      }

      const platformExists = await this.prismaService.platform.findUnique({
        where: { id: platformId },
      });
      if (!platformExists) {
        throw new BadRequestException(
          `Platform with ID ${platformId} not found`,
        );
      }

      const cookie = await this.prismaService.cookie.create({
        data: {
          name: name,
          filename: file.originalname,
          content: file.buffer.toString('utf-8'), // Buffer directly from file
          platformId,
        },
      });

      return JSON.stringify({
        id: cookie.id,
        name: cookie.name,
        filename: cookie.filename,
        content: cookie.content.toString(), // No args, defaults to 'utf8'
        platformId: cookie.platformId,
        createdAt: cookie.createdAt,
      });
    } catch (error) {
      throw new BadRequestException(
        `Failed to upload cookie: ${error.message}`,
      );
    }
  }
  @Get('list')
  async listCookies() {
    const cookies = await this.cookieService.getAllCookieWithPlatformName();
    //const cookies = await this.prismaService.cookie.findMany({});
    return JSON.stringify(cookies);
  }
  @Delete(':id')
  async deleteCookie(@Param('id', ParseIntPipe) id: number) {
    return this.cookieService.deleteCookie(id);
  }

  // Get Cookie by ID
  @Get(':id')
  async getCookie(
    @Param('id', ParseIntPipe) cookieId: number,
  ): Promise<CookieResponseDto> {
    try {
      return this.cookieService.getCookieWithPlatformName(cookieId);
    } catch (err) {
      throw new NotFoundException(`Cookie with ID ${cookieId} not found`);
    }
  }
  // const cookie = await this.prismaService.cookie.findUnique({
  //     where: { id },
  //   });

  //   if (!cookie) {
  //     throw new NotFoundException(`Cookie with ID ${id} not found`);
  //   }

  //   return {
  //     id: cookie.id,
  //     name: cookie.name,
  //     content: cookie.content.toString(), // No args, defaults to 'utf8'
  //     platformId: cookie.platformId,
  //     createdAt: cookie.createdAt,
  //   };
  // }
}
